package org.teiid.resource.adapter.cassandra;

import javax.resource.ResourceException;

import org.teiid.logging.LogConstants;
import org.teiid.logging.LogManager;
import org.teiid.resource.spi.BasicConnection;
import org.teiid.translator.cassandra.CassandraConnection;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;

/**
 * Represents a connection to Cassandra NoSql database.
 * @author Kouba
 * */
public class CassandraConnectionImpl extends BasicConnection implements CassandraConnection{
	private CassandraManagedConnectionFactory config;
	private Cluster cluster = null;
	private Session session = null;
	private Metadata metadata = null;

	public CassandraConnectionImpl(CassandraManagedConnectionFactory config) {
		this.config = config;
		
		//connect to cluster at given adress
		cluster = Cluster.builder()
	            .addContactPoint(config.getAdress()).build();
		
		metadata = cluster.getMetadata();
		
		//get session from the cluster and its specified keyspace to session field
		session = cluster.connect(config.getKeyspace());
	}

	@Override
	public void close() throws ResourceException {
		if(cluster != null){
			cluster.shutdown();
		}
		LogManager.logInfo(LogConstants.CTX_CONNECTOR, CassandraManagedConnectionFactory.UTIL.
				getString("shutting_down")); //$NON-NLS-1$
	}
	
	@Override
	public boolean isAlive() {
		LogManager.logInfo(LogConstants.CTX_CONNECTOR, CassandraManagedConnectionFactory.UTIL.
				getString("alive")); //$NON-NLS-1$
		return true;
	}
	
	@Override
	public ResultSet executeQuery(String query){
		return session.execute(query);
	}

	@Override
	public KeyspaceMetadata keyspaceInfo() {
		System.out.println("I AM IN CONNIMPL");
		return metadata.getKeyspace(config.getKeyspace());
	}

}
